﻿
var express = require('express')
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);

app.use(express.json({ limit : '800mb' }))

app.use('/api/static',express.static('./eshop'))

// 解决跨域请求
app.use(require('cors')())

const sendRes = {}

io.on('connection', (socket) => {
    console.log('@主房间');
    socket.on('send', function (data) {
        try{
            sendRes[data.code].send(data.data)
            delete sendRes[data.code]
        }catch(e){
            console.log(e);
        }
    });
});


io.on('disconnect',() => {
    console.log("断开连接");
})


app.use('/**', function(req, res){
    // 请求路劲
    let code = guid()
    var data = {
        url : req.originalUrl,
        port : req.headers.serverPort || '8008',
        host : req.headers.serverHost || 'http://127.0.0.1',
        data : req.body,
        code,
        method : req.method,
        // headers : {
        //     "Authorization" : req.headers.authorization,
        //     "Accept": 'application/json, text/plain, */*',
        //     "Accept-Encoding": 'gzip, deflate',
        //     "Accept-Language": 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        //     "Connection": 'keep-alive',
        //     "Content-Length": '41',
        //     "Content-Type": 'application/json;charset=UTF-8'
        // }
        headers : req.headers
    }
    try{
        sendRes[code] = res
        io.emit('send', data)
    }catch(e){
        console.log(e);
    }
})
server.listen(4000,()=>{
    console.log("http://127.0.0.1:4000");
});
function guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
        return v.toString(16);
    });
}